package com.shujia.jinjie;

import com.shujia.entity.User;
import com.shujia.utils.CodeTool;
import com.shujia.utils.MySQLTool;
import com.shujia.utils.RedisTool;
import com.shujia.utils.TemplateCodeModel;
import redis.clients.jedis.JedisCluster;

import java.sql.*;
import java.util.Scanner;

/*
    sql注入的问题
 */

public class IODemo2 {
    public static void init() {
        System.out.println("=============== 欢迎来到李刚博彩城！！ ================");
        System.out.println("-------------------");
        System.out.println("菜单：");
        System.out.println("1. 登录");
        System.out.println("2. 注册");
        System.out.println("3. 修改信息");
        System.out.println("-------------------");
        Scanner sc = new Scanner(System.in);
        System.out.print("您要做的操作选项：");
        int choice = sc.nextInt();
        switch (choice) {
            case 1:
                login();
                break;
            case 2:
                //TODO: 注册用户，加入验证码的功能，且每个人的手机号不能重复
                register();
                break;
            case 3:
                //TODO: 修改信息【只能修改密码，不能修改用户名】
                //update();
                break;
            default:
                System.out.println("没有该选项...欢迎下次使用！");
        }
    }

    public static void register() {
        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>注册操作进行中");
        Scanner sc = new Scanner(System.in);
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("######## 欢迎注册李刚博彩城 ^_< ########");
        System.out.print("请设置新用户名: ");
        String name = sc.nextLine();
        //TODO: 这里需要读取配置文件获取用户和密码
        if (isUserExistWithName(name)) {
            System.out.println("该用户名已经存在！");
            return;
        }

        System.out.print("请设置新用户的密码: ");
        String password = sc.nextLine();

        saveUser(name, password);
    }

    public static void saveUser(String username, String password) {
        Connection conn = null;
        Statement statement = null;

        try {
            conn = MySQLTool.getConnection();
            statement = conn.createStatement();

            int id = 0;
            ResultSet resultSet = statement.executeQuery("select max(id) as maxId from sjusers");
            while (resultSet.next()) {
                id = Integer.parseInt(resultSet.getString(1)) + 1;
            }
            String sql = "insert into sjusers values(" + id + ",'" + username + "','" + password + "')";
            int i = statement.executeUpdate(sql);
            if (i == 1) {
                System.out.println("用户保存成功！！");
            } else {
                System.out.println("用户保存失败！！");
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    public static void login() {
        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>登录操作进行中");
        Scanner sc = new Scanner(System.in);
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("######## 欢迎登录李刚博彩城 ^_< ########");
        System.out.print("请输入您的用户名: ");
        String name = sc.nextLine();
        if (!isUserExistWithName(name)) {
            System.out.println("该用户不存在, 请先注册！");
            return;
        }

        System.out.println("选择登录的方式：【1.密码登录 2.手机号验证码登录】");

        int choice = sc.nextInt();
        if (choice == 1) {
            System.out.print("请输入您的密码: ");
            String password = sc.next();
            //TODO: 这里需要读取数据库表获取用户和密码
            User user = getUserWithNameAndPassword(name, password);

            if (user != null) {
                System.out.println("登录成功！美女荷官，在线发牌....");
                shouYe();
            } else {
                System.out.println("您输入的密码错误！！！已退出...");
            }
        } else if (choice == 2) {
            System.out.print("请输入接收验证码的手机号: ");
            String phoneNum = sc.next();
            //根据手机号查询用户信息
            User user = getUserWithPhoneNum(phoneNum);
            if (user != null) {
                while (true){
                    System.out.println("点击获取验证码：【数字1:确认发送  其它数值:取消发送】");
                    int i = sc.nextInt();
                    if(i==1){
                        // 调用发送验证码的功能
                        String code1 = CodeTool.createCode();
                        // 存入到redis中，并设置过期时间
                        JedisCluster jedisCluster = RedisTool.getConnection();
                        jedisCluster.setex("yzm_" + phoneNum, 60, code1);
                        boolean b = CodeTool.sendCode(phoneNum, TemplateCodeModel.TEMP_32, code1);
                        if (b) {
                            System.out.println("验证码已发送.....");
                            System.out.print("请输入收到验证码：");
                            String code2 = sc.next();
//                            int code2 = sc.nextInt();
                            //获取redis中的验证码
                            String redisCode = jedisCluster.get("yzm_" + phoneNum);
                            System.out.println("----------"+redisCode+"----------");
                            if(redisCode==null){
                                System.out.println("验证码已经过期！请重新获取。。。");
                            }else if (redisCode.equals(code2)){
                                System.out.println("登录成功！美女荷官，在线发牌....");
                                shouYe();
                                break;
                            } else {
                                System.out.println("验证码不正确！请重新获取！");
                            }
                        }
                    }else {
                        System.out.println("登录取消！");
                        break;
                    }
                }
            } else {
                System.out.println("您输入的手机号错误！！！已退出...");
            }
        }
    }

    public static void shouYe(){
        try {
            Scanner sc = new Scanner(System.in);
            System.out.println("请输入要查询的商品完整名称：");
            String name = sc.nextLine();

            //先去redis中查询
            JedisCluster jedisCluster = RedisTool.getConnection();
            String nameInfo = jedisCluster.get(name);
            if(nameInfo==null){
                System.out.println("============走的是mysql查询==============");
                Connection conn = MySQLTool.getConnection();
                PreparedStatement preparedStatement = conn.prepareStatement("select * from jd_goods where goods_name=?");
                preparedStatement.setString(1,name);

                ResultSet resultSet = preparedStatement.executeQuery();
                while (resultSet.next()){
                    String goods_name = resultSet.getString(1);
                    String price = resultSet.getString(2);
                    String shop = resultSet.getString(3);
                    String icos = resultSet.getString(4);
                    String info = goods_name+"|"+price+"|"+shop+"|"+icos;
                    System.out.println(info);
                    jedisCluster.setex(goods_name,86400,info);
                }
            }else {
                System.out.println("============走的是redis查询==============");
                System.out.println(nameInfo);
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    public static boolean isUserExistWithName(String name) {
        Connection conn = null;
        Statement statement = null;
        boolean flag = false;
        try {
            conn = MySQLTool.getConnection();
            statement = conn.createStatement();

            ResultSet resultSet = statement.executeQuery("select name,password from sjusers where name='" + name + "'");
            if (resultSet.next()) {
                flag = true;
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

        return flag;
    }

    public static User getUserWithPhoneNum(String phoneNum) {
        Connection conn = null;
//        Statement statement = null;
        PreparedStatement preparedStatement = null;
        User user = null;
        try {
            conn = MySQLTool.getConnection();

            String sql = "select name,password from sjusers where phoneNum=?"; // ?相当于占位符
            preparedStatement = conn.prepareStatement(sql);
            preparedStatement.setString(1, phoneNum);

//            System.out.println(sql);
//            ResultSet resultSet = statement.executeQuery(sql);
            ResultSet resultSet = preparedStatement.executeQuery();

            if (resultSet.next()) {
                String username = resultSet.getString("name");
                String password = resultSet.getString("password");
                user = new User(username, password);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (preparedStatement != null) {
                try {
                    preparedStatement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

        return user;
    }


    public static User getUserWithNameAndPassword(String name, String pwd) {
        Connection conn = null;
//        Statement statement = null;
        PreparedStatement preparedStatement = null;
        User user = null;
        try {
            conn = MySQLTool.getConnection();
//            statement = conn.createStatement();


//            String sql = "select name,password from sjusers where name='" + name + "' and password='" + pwd + "'";
            //select name,password from sjusers where name='ligang' and password='dsa' or '1'='1'
            //"select name,password from sjusers where name=? and password=?";
            String sql = "select name,password from sjusers where name=? and password=?"; // ?相当于占位符
            preparedStatement = conn.prepareStatement(sql);
            preparedStatement.setString(1, name);
            preparedStatement.setString(2, pwd);

//            System.out.println(sql);
//            ResultSet resultSet = statement.executeQuery(sql);
            ResultSet resultSet = preparedStatement.executeQuery();

            if (resultSet.next()) {
                String username = resultSet.getString("name");
                String password = resultSet.getString("password");
                user = new User(username, password);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (preparedStatement != null) {
                try {
                    preparedStatement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

        return user;

    }

//    public static Set<User> getAllUsers(){
//        HashSet<User> users = new HashSet<>();
//        try {
//            Connection conn = MySQLTool.getConnection();
//            //TODO:查询数据库获取所有的用户
//            Statement state = conn.createStatement();
//
//
//
//        }catch (Exception e){
//            e.printStackTrace();
//        }
//
//        return users;
//    }

    public static void main(String[] args) {
        init();
    }
}
